package bud.taskmanager.project.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;

import bud.taskmanager.project.dto.Project;


@Repository(value = "ProjectDao")
public class ProjectDao {

	@Autowired
	private SimpleJdbcTemplate template;

	public List<Project> findAllProjects() {
		return template
				.query("SELECT ID, NAME, DESCRIPTION, IS_PUBLIC, CREATED_ON, UPDATED_ON, IDENTIFIER, STATUS FROM PROJECTS ORDER BY CREATED_ON ASC",
						new BeanPropertyRowMapper<Project>(Project.class));
	}

	public void createProject(Project project) {
		template.update(
				"INSERT INTO PROJECTS (NAME, DESCRIPTION, CREATED_ON, IDENTIFIER) VALUES (:name, :description, CURRENT_TIMESTAMP, :identifier)",
				new BeanPropertySqlParameterSource(project));
	}

	public void updateProject(Project project) {
		template.update(
				"UPDATE PROJECTS SET NAME=:name, DESCRIPTION=:description, IDENTIFIER=:identifier, UPDATED_ON=CURRENT_TIMESTAMP WHERE ID=:id",
				new BeanPropertySqlParameterSource(project));
	}

	public void deleteProject(int id) {
		template.update("DELETE FROM PROJECTS WHERE ID=?", id);
	}

	public Project findProject(int id) {
		return template
				.queryForObject(
						"SELECT ID, NAME, DESCRIPTION, IS_PUBLIC, CREATED_ON, UPDATED_ON, IDENTIFIER, STATUS FROM PROJECTS WHERE ID=?",
						new BeanPropertyRowMapper<Project>(Project.class), id);
	}
}
